<?php
//此文档为算法赛报名页
require_once("./bm_header.php");
$is_admin = isset($_SESSION['administrator']) || isset($_SESSION[$BM_ADMIN]);
global $TeamBool;
if (isset($_GET['cid'])) 
{
    $cid = intval($_GET['cid']);
    require_once("./judgecid.php"); //判断查看权限、比赛id合法性等等非正常访问
    if($user_active0 == 'N')
    {
    	?>
    	
		<div class="content bolr">
		<style type="text/css">
		<!--
		.STYLE1 {color: #FF3300}
		-->
		</style>
		<h2 class="h2">您尚未获得注册算法设计竞赛的权限。</h2>
      	<div class="middle">
          <table border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td height="30">&nbsp;</td>
              <td height="30" colspan="2" align="left"><span class="STYLE1">用户注册：点击页眉“【<strong><a href="<?php echo $BM_HOME."/registerpage.php";?>">注册教练帐号</a></strong>】”按要求认真填写信息后提交。</span></td>
            </tr>
            <tr>
              <td height="30">&nbsp;</td>
              <td height="30" colspan="2" align="left"><span class="STYLE1">用户激活：登录后点击页眉“【<strong><a href="<?php echo $BM_HOME."/userinfo.php";?>">查看帐号信息</a></strong>】”，上传有相关单位公章的身份证明文件的清晰扫描或拍照附件（打包为RAR或ZIP格式上传），管理员会定期检查公文并激活用户。</span></td>
            </tr>
          </table>
         </div>
		<div style="height:150px;"></div>
		</div>
		<?php 
		require_once("./bm_footer.php");
        exit(0);
    }
	$sql    = "SELECT * FROM `cr_contest` WHERE `contest_id`='$cid' ";
	$result = mysql_query($sql);
	$row    = mysql_fetch_object($result);
	$now    = time();
	$start  = strtotime($row->contest_0_start);
	$end    = strtotime($row->contest_0_end);
	$view_description = $row->contest_0_description;
	mysql_free_result($result);
	$view_start = $view_start_time0;
	$view_end = $view_end_time0;
	
    /*******************增加队伍，即_GET有func域为team***************************/
    if (isset($_GET['func']) && $_GET['func'] == 'team') 
	{
		
        if ($now < $contest_0_start) 
        {
			require_once("bm_footer.php");
            echo "<script language='javascript'>\n";
            echo "alert('注册尚未开始!');\n";
            echo "history.go(-1);\n";
            echo "</script>";
            exit(0);
        }
        if ($now > $contest_0_end) 
        {
			require_once("bm_footer.php");
            echo "<script language='javascript'>\n";
            echo "alert('注册已结束!');\n";
            echo "history.go(-1);\n";
            echo "</script>";
            exit(0);
        }
        $sql    = "SELECT * FROM `cr_contest` WHERE `contest_id`='$cid' ";
        $result = mysql_query($sql);
        $row    = mysql_fetch_object($result);
        $now    = time();
        $start  = strtotime($row->contest_0_start);
        $end    = strtotime($row->contest_0_end);
        $view_description = $row->contest_0_description;
        mysql_free_result($result);
        $team_cid = $cid;
		
        $user_id = $_SESSION['user_id'];
        //读教练信息
        $sql     = "SELECT * FROM `cr_user` WHERE `user_id`='$user_id' ";
        $result  = mysql_query($sql);
        $row     = mysql_fetch_object($result);
        $user_school  = $row->user_school;
        mysql_free_result($result);
        
        if (isset($_GET['tid'])) //如果GET到队伍编号team_id即tid，则是修改信息，否则是增加队伍
        {
            global $TeamBool;
            $TeamBool = true;
            $team_id  = $_GET['tid'];
            $sql      = "SELECT * FROM `cr_team` WHERE `team_id`='$team_id' AND `team_kind` = '0' AND `team_cid`='$cid'";
            $result   = mysql_query($sql);
            $rows_cnt = mysql_num_rows($result);
            if ($rows_cnt == 0) 
            {
				require_once("bm_footer.php");
                echo "<script language='javascript'>\n";
                echo "alert('没有这样一支队伍!');\n";
                echo "history.go(-1);\n";
                echo "</script>";
                mysql_free_result($result);
                exit(0);
            }
            $row = mysql_fetch_object($result);
            if ($row->team_school != $user_school) //如果教练不是这个队伍的学校的（只有通过修改get的网址才会遇到这情况）
            {
				require_once("bm_footer.php");
                echo "<script language='javascript'>\n";
                echo "alert('没有修改权限!');\n";
                echo "history.go(-1);\n";
                echo "</script>";
                mysql_free_result($result);
                exit(0);
            }
            $team_name   = $row->team_name;
            $team_school = $row->team_school;
            $team_coach  = $row->team_coach; //这个不是注册这个team的user，而是注册填表的领队，一个教练注册的几个队伍可以有不同领队
            $team_phone  = $row->team_phone;
            mysql_free_result($result);
            $sql    = "
					SELECT * FROM `cr_team`, `cr_stu` 
					WHERE `cr_team`.`team_id`=`cr_stu`.`team_id` AND `cr_team`.`team_id`='$team_id' 
					ORDER BY `stu_123` ASC
					";
            
            //stu_123是一个队的多个队员适当排一下顺序
            $result = mysql_query($sql);
            for ($i = 0; $i < 3; $i++) 
            {
                $row            = mysql_fetch_object($result);
                $stu_card[$i]   = SqlToHtml($row->stu_card);
                $stu_number[$i] = SqlToHtml($row->stu_number);
                $stu_name[$i]   = SqlToHtml($row->stu_name);
                $stu_major[$i]  = SqlToHtml($row->stu_major);
                $stu_grade[$i]  = SqlToHtml($row->stu_grade);
                $stu_sex[$i]    = SqlToHtml($row->stu_sex);
                $stu_cloth[$i]  = SqlToHtml($row->stu_cloth);
            }
        } 
		else 
		{
            global $TeamBool;
            $TeamBool = false;
            $sql      = "SELECT * FROM `cr_team` WHERE `team_kind` = '0' AND `team_school`='$user_school'  AND `user_id`='$user_id' AND `team_cid`='$cid'";
            $result   = mysql_query($sql);
            $rows_cnt = mysql_num_rows($result);
            if ($rows_cnt >= $SF_TEAM_LIMIT) 
            {
				require_once("bm_footer.php");
                echo "<script language='javascript'>\n";
                echo "alert('已到达报名队数限制，不能增加队伍!');\n";
                //echo "window.location.href='" . $BM_HOME . "/suanfa.php?cid=$cid';\n";
                echo "history.go(-1);\n";
                echo "</script>";
                exit(0);
            }
            
        }
        
        if (isset($_POST['do'])) 
        {
            if ($now < $start || $now > $end) 
            {
				require_once("bm_footer.php");
                echo "<script language='javascript'>\n";
                echo "alert('不在注册时间范围内，提交无效!');\n";
                echo "history.go(-1);\n";
                echo "</script>";
                exit(0);
            }
            $vcode = trim($_POST['vcode']);
            if ($BM_VCODE && ($vcode != $_SESSION["vcode"] || $vcode == "" || $vcode == null)) 
            {
				require_once("bm_footer.php");
                echo "<script language='javascript'>\n";
                echo "alert('验证码输入错误!');\n";
				$_POST = NULL;
                echo "history.go(-1);\n";
                echo "</script>";
                exit(0);
            }
            require_once("./include/check_post_key.php");
            $team_name  = myMQpro($_POST['team_name']);
            $team_coach = myMQpro($_POST['team_coach']);
            $team_phone = myMQpro($_POST['team_phone']);
            
			//先记录学生信息并查询是否学生重复注册比赛
            for ($i = 0; $i < 3; $i++) 
			{
                $stu_card[$i]   = myMQpro($_POST['stu_card' . $i]);
                $stu_number[$i] = myMQpro($_POST['stu_number' . $i]);
                $stu_name[$i]   = myMQpro($_POST['stu_name' . $i]);
                $stu_school[$i] = myMQpro($user_school);
                $stu_major[$i]  = myMQpro($_POST['stu_major' . $i]);
                $stu_grade[$i]  = myMQpro($_POST['stu_grade' . $i]);
                $stu_sex[$i]    = myMQpro($_POST['stu_sex' . $i]);
                $stu_cloth[$i]  = myMQpro($_POST['stu_cloth' . $i]);
                $sql            = "SELECT * FROM `cr_stu`, `cr_team` WHERE `cr_stu`.`stu_card`='$stu_card[$i]' AND `cr_stu`.`team_id`=`cr_team`.`team_id` AND `cr_team`.`team_cid`=$cid";
                $result         = mysql_query($sql);
                $rows_cnt       = mysql_num_rows($result);
                if ($rows_cnt > 0 && (!$TeamBool || $team_id != mysql_fetch_object($result)->team_id)) 
				{
                    echo "<script language='javascript'>\n";
                    echo "alert('学生".$stu_name[$i]."(身份证号:".$stu_card.")已注册其他比赛或队伍！同次赛事一名学生只能参加一项比赛。');\n";
					if(isset($_GET['tid']))
						echo "window.location.href='".$BM_HOME."/suanfa.php?cid=$cid&tid=$team_id&func=team'\n";
					else
						echo "window.location.href='".$BM_HOME."/suanfa.php?cid=$cid&func=team'\n";
                    //echo "history.go(-1);\n";
                    echo "</script>";
                    mysql_free_result($result);
					require_once("bm_footer.php");
                    exit(0);
                }
            }
			
            if ($TeamBool) //修改信息
            {
                //更新队伍信息
                $sql = "UPDATE `cr_team` set `team_school`='$user_school', `team_name`='$team_name',`team_coach`='$team_coach' ,`team_phone`='$team_phone'WHERE `team_id`=$team_id";
                mysql_query($sql); // or die(mysql_error());
            } 
			else //增加信息
            {
                //插入队伍
                $sql = "INSERT INTO `cr_team`(`team_name`,`team_school`,`team_cid`,`team_coach`,`team_phone`,`team_kind`, `user_id`)
VALUES('$team_name','$user_school','$team_cid','$team_coach','$team_phone', '0', '$user_id')"; //team_kind为0，表示是算法竞赛的team，这个标记在查询的时候用
                mysql_query($sql); // or die(mysql_error());
                $team_id = mysql_insert_id();
            }
            for ($i = 0; $i < 3; $i++) 
			{
                if ($TeamBool) //修改信息
                {
                    $sql = "UPDATE `cr_stu` set `stu_card`='$stu_card[$i]',`stu_number`='$stu_number[$i]',`stu_name`='$stu_name[$i]',`stu_school`='$stu_school[$i]',`stu_major`='$stu_major[$i]',`stu_grade`='$stu_grade[$i]',`stu_sex`='$stu_sex[$i]',`stu_cloth`='$stu_cloth[$i]' WHERE `team_id`='$team_id' AND `stu_123`=$i";
                    mysql_query($sql); // or die(mysql_error());
                } 
				else //增加信息
                {
                    $sql = "INSERT INTO `cr_stu`(`stu_card`, `stu_number`, `stu_name`, `stu_school`, `stu_major`, `stu_grade`, `stu_sex`, `stu_cloth`, `team_id`, `stu_123`) 
                    		VALUES('$stu_card[$i]','$stu_number[$i]','$stu_name[$i]','$stu_school[$i]','$stu_major[$i]','$stu_grade[$i]','$stu_sex[$i]','$stu_cloth[$i]','$team_id','$i')";
                    mysql_query($sql); // or die(mysql_error());
                }
                
            }
            ?>
				<script language='javascript'>
				alert('提交成功!');
				window.location="<?php echo $BM_HOME."/suanfa.php?cid=".$cid;?>";
				</script>";
			<?php 
            header("Location: ./suanfa.php?cid=" . $cid);
        }
        
        
        if ($TeamBool) 
        {
            $team_name   = ($team_name);
            $team_school = ($team_school);
            $team_coach  = ($team_coach);
            for ($i = 0; $i < 3; $i++) 
            {
                $stu_card[$i]   = ($stu_card[$i]);
                $stu_number[$i] = ($stu_number[$i]);
                $stu_name[$i]   = ($stu_name[$i]);
                $stu_major[$i]  = ($stu_major[$i]);
                $stu_grade[$i]  = ($stu_grade[$i]);
                $stu_sex[$i]    = ($stu_sex[$i]);
                $stu_cloth[$i]  = ($stu_cloth[$i]);
            }
        }
		require_once("template/".$BM_TEMPLATE."/suanfa_info.php");
    }
    else if (isset($_GET['func']) && $_GET['func'] == 'doc') 
    {
		$team_id = $_GET['tid'];
		$sql      = "SELECT * FROM `cr_team` WHERE `team_id`='$team_id' AND `team_kind` = 0";
	    $result   = mysql_query($sql);
	    $rows_cnt = mysql_num_rows($result);
	    if ($rows_cnt == 0) 
	    {
	        echo "<script language='javascript'>\n";
	        echo "alert('队伍编号错误!');\n";
	        echo "history.go(-1);\n";
	        echo "</script>";
	        mysql_free_result($result);
	        exit(0);
	    }
	    $row = mysql_fetch_object($result);
	    if ($row->team_cid != $cid) 
	    {
	        echo "<script language='javascript'>\n";
	        echo "alert('队伍编号错误!');\n";
	        echo "history.go(-1);\n";
	        echo "</script>";
	        mysql_free_result($result);
	        exit(0);
	    }
	    $team_name   = SqlToHtml($row->team_name);
	    $team_school = SqlToHtml($row->team_school);
	    $team_cid    = SqlToHtml($row->team_cid);
	    $team_coach  = SqlToHtml($row->team_coach);
	    $team_phone  = SqlToHtml($row->team_phone);
	    $team_upload = SqlToHtml($row->team_upload);
	    
	    
	    if ($user_school != $team_school) 
	    {
	        echo "<script language='javascript'>\n";
	        echo "alert('没有查看权限!');\n";
	        echo "history.go(-1);\n";
	        echo "</script>";
	        mysql_free_result($result);
	        exit(0);
	    }
	    
	    mysql_free_result($result);
	    
	    $longmsg = "</br>";
	    if (isset($_POST['do'])) 
	    {
	        if ($now < $contest_0_start || $now > $contest_0_end) 
	        {
	            echo "<script language='javascript'>\n";
	            echo "alert('不在注册时间，不能修改或上传文档!');\n";
	            echo "history.go(-1);\n";
	            echo "</script>";
	            mysql_free_result($result);
	            exit(0);
	        }
	        $oldfile   = $_FILES['file']['name']; //获取文件上传之前的全名
	        $arr       = explode(".", $oldfile); //将文件以.为分隔转换为数组变量
	        $key       = count($arr) - 1; //获取数组就量的最后一个变量键
	        $flextends = $arr[$key]; //获取上传前的文件扩展名
	        $ext       = strtolower($flextends); //算出文件的扩展名并进行大小写转换
	        
	        if ($ext != "rar" && $ext != "zip") 
			{
	            $longmsg.=".$ext 文件不符合要求";
	        } 
			else if($_FILES["file"]["size"] > $XM_SIZE_LIMIT)
			{
				 $longmsg.="文档超出限制大小";
			}
			else if ((($_FILES["file"]["type"] == "application/octet-stream") || ($_FILES["file"]["type"] == "application/x-zip-compressed")) && ($_FILES["file"]["size"] < $XM_SIZE_LIMIT)) //限制文件上传格式和大小
	        {
	            if ($_FILES["file"]["error"] > 0) 
				{
	                $longmsg.="Return Code: " . $_FILES["file"]["error"] . "<br />";
	            } 
				else 
				{
	                $longmsg.="文件名: " . $_FILES["file"]["name"] . "<br />";
	                $longmsg.="文件格式: " . $_FILES["file"]["type"] . "<br />";
	                $longmsg.="文件大小: " . ($_FILES["file"]["size"] / 1024) . " KB<br />";
	                //    $longmsg.="缓存文件夹: " . $_FILES["file"]["tmp_name"];
	                $rar_zip;
	                if ($_FILES["file"]["type"] == "application/octet-stream") {
	                    $rar_zip                = "rar";
	                    $_FILES["file"]["name"] = $team_id . ".rar";
	                } else if ($_FILES["file"]["type"] == "application/x-zip-compressed") {
	                    $rar_zip                = "zip";
	                    $_FILES["file"]["name"] = $team_id . ".zip";
	                }
	                
	                
	                move_uploaded_file($_FILES["file"]["tmp_name"], $UPLOAD_ROUT . $_FILES["file"]["name"]);
	                $longmsg.="文件成功上传";
	                
	                $team_upload = myMQpro($DOWNLOAD_ROUT . "?file=" . $team_id . "&rz=" . $rar_zip);
	                $sql         = "UPDATE `cr_team` set `team_upload` = '$team_upload' WHERE `team_id`=$team_id";
	                mysql_query($sql); // or die(mysql_error());
	                
	            }
	        } 
			else 
			{
	            $longmsg.="文件不符合要求";
	        }
	    }
		require_once("template/".$BM_TEMPLATE."/suanfa_doc.php");
	}
    	
    /*******************查看队伍列表，即_GET没有func域***************************/
    else 
	{
        $user_id = $_SESSION['user_id'];
        
        //读教练信息
        $sql    = "SELECT * FROM `cr_user` WHERE `user_id`='$user_id' ";
        $result = mysql_query($sql);
        $row    = mysql_fetch_object($result);
        $user_school = $row->user_school;
        mysql_free_result($result);
        $sum_team      = 0;
        $sql    = "SELECT * FROM `cr_team` WHERE `user_id`='$user_id' AND `team_kind`=0 AND `team_cid`='$cid'";
        $result = mysql_query($sql);
        while ($row = mysql_fetch_object($result)) 
        {
            $team_name[$sum_team] = SqlToHtml($row->team_name);
            $team_coach[$sum_team] = SqlToHtml($row->team_coach);
            $team_phone[$sum_team] = SqlToHtml($row->team_phone);
            $team_id[$sum_team] = SqlToHtml($row->team_id);
            $sum_team ++;
        }
		require_once("template/".$BM_TEMPLATE."/suanfa_list.php");
     }
} 
else 
{
    echo "<script language='javascript'>\n";
    echo "alert('这儿什么都没有~~');\n";
    echo "history.go(-1);\n";
    echo "</script>";
	require_once("bm_footer.php");
    exit(0);
}

require_once("bm_footer.php");
?>
